package org.algorithm.二师兄.数组.三月.第三周;

import java.lang.reflect.Array;
import java.util.*;

/**
 * @author zhx
 * @version 1.0
 * @date 2022/03/16 9:08 PM
 * @description:
 *
 *
 * url: https://leetcode-cn.com/problems/frequency-of-the-most-frequent-element/
 */
public class 最高频元素的频数 {

    public static void main(String[] args) {
        int[] nums = {1,4,8,13};
        System.out.println(maxFrequency(nums, 5));
        System.out.println(maxFrequency1(nums, 5));
    }

    public static int maxFrequency(int[] nums, int k){
        int n = nums.length;
        Map<Integer, Integer> map = new HashMap<>();
        for (int i : nums) map.put(i, map.getOrDefault(i, 0) + 1);
        List<Integer> list = new ArrayList<>(map.keySet());
        Collections.sort(list);
        int ans = 1;
        for (int i = 0; i < list.size(); i++) {
            int x = list.get(i), cnt = map.get(x);
            if (i > 0) {
                int p = k;
                for (int j = i - 1; j >= 0; j--) {
                    int y = list.get(j);
                    int diff = x - y;
                    if (p >= diff) {
                        int add = p / diff;
                        int min = Math.min(map.get(y), add);
                        p -= min * diff;
                        cnt += min;
                    } else {
                        break;
                    }
                }
            }
            ans = Math.max(ans, cnt);
        }
        return ans;
    }


    static int[] nums;
    static int[] sum;
    static int n, k;

    public static int maxFrequency1(int[] _nums, int _k){
        // 从小到大排序
        // 如果存在真实最优解, 意味着存在着一个长度为len的区间[left, right]
        nums = _nums;
        k = _k;
        n = nums.length;
        Arrays.sort(nums);
        sum = new int[n + 1];
        for (int i = 1; i <= n; i++) sum[i] = sum[i - 1] + nums[i - 1];
        int l = 0, r = n;
        while (l < r) {
            int mid = l + r + 1 >> 1;
            if (check(mid)) l = mid;
            else r = mid - 1;
        }
        return r;
    }

    static boolean check(int len) {
        for (int l = 0; l + len - 1 < n; l++) {
            int r = l + len - 1;
            int cur = sum[r + 1] - sum[l];
            int t = nums[r] * len;
            if (t - cur <= k) return true;
        }
        return false;
    }
}
